package com.shuai.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuai.domain.Weather;
import com.shuai.project.model.WeatherParams;
import com.shuai.domain.CityCode;
import com.shuai.mapper.CityCodeMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName WeatherController
 * @Description TODO 
 * @Date 2023/5/1 17:01
 */

@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Resource
    private CityCodeMapper cityCodeMapper;

    public static final String WEATHER_URL = "http://t.weather.itboy.net/api/weather/city/";


    @PostMapping("/weatherInfo")
    public String getWeatherInfoByPost(@RequestBody WeatherParams weatherParams, HttpServletRequest request){
        String city = weatherParams.getCity();
        boolean flag = city.endsWith("市");
        if (flag){
            city = city.substring(0,city.lastIndexOf("市"));
        }
        LambdaUpdateWrapper<CityCode> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(CityCode::getCity, city);
        CityCode cityCode = cityCodeMapper.selectOne(lqw);
        Long code = cityCode.getCode();
        String str = HttpUtil.get(WEATHER_URL + code);
        LinkedHashMap linkedHashMap = JSONUtil.toBean(str, LinkedHashMap.class);
        return JSONUtil.toJsonStr(linkedHashMap.get("data"));
    }
}
